package com.lwl.blog.web.service.impl;

import com.lwl.blog.web.constans.RedisKey;
import com.lwl.blog.web.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 点赞业务实现类
 * </p>
 *
 * @author lwl
 * @since 22-12-28
 */

@Service
public class LikeService {

    //连接radis
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //点赞功能
    public void clickLike(LikeVo likeVo) {

        //1.准备点赞得key
        String likeKey = String.format(RedisKey.LIKE_KEY, likeVo.getEntityType(), likeVo.getEntityId());
        String userKey = String.format(RedisKey.USER_LIKE_NUM_KEY, likeVo.getEntityUserId());

        //2.判断用户是否对该帖作者点赞
        SetOperations<String, String> setOperations = stringRedisTemplate.opsForSet();
        ValueOperations<String, String> ValueOperations = stringRedisTemplate.opsForValue();
        Boolean member = setOperations.isMember(likeKey, likeVo.getUserId().toString());

        if (member) {

            //用户已经点过赞了，取消点赞
            setOperations.remove(likeKey, likeVo.getUserId().toString());
            //对应作者的赞自动减一
            ValueOperations.decrement(userKey);

        } else {

            //3.没有就点个赞
            setOperations.add(likeKey, likeVo.getUserId().toString());
            //4.对应作者的赞加1
            ValueOperations.increment(userKey);

        }

    }


    //获得点赞id
    public Long getInvitataionLikeCount(Integer id) {

        String key = String.format(RedisKey.LIKE_KEY, 1, id);
        return stringRedisTemplate.opsForSet().size(key);
    }

    //判断用户是否点赞
    public Boolean getInvitataionUserLike(Integer userId, Integer intaId) {

        String key = String.format(RedisKey.LIKE_KEY, 1, intaId);
        return stringRedisTemplate.opsForSet().isMember(key, userId.toString());

    }

    //查询是否点赞
    public Boolean isLike(LikeVo likeVo) {

        String key = String.format(RedisKey.LIKE_KEY, 1, likeVo.getEntityId());
        return stringRedisTemplate.opsForSet().isMember(key, likeVo.getUserId().toString());
    }
}
